package com.example.mygis.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.mygis.dao.*;
import com.example.mygis.entity.*;
import com.example.mygis.service.AmapUtil;
import com.example.mygis.service.QyNdxxService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;


/**
 * @Description: TODO
 * @author: Gread
 * @date: 2021年03月29日 22:25
 */

@RestController
@RequestMapping("mygis")
@Data
@Slf4j
public class GisController {

    @Autowired
    private QyNdxxMapper ndxxDao;
    @Autowired
    private QyCxzyMdMapper cxzyMdMapper;
    @Autowired
    private QyXwyqDao qyXwyqDao;
    @Autowired
    private QyCggDao qyCggDao;
    @Autowired
    private QyNdxxService qyNdxxService;
    @Autowired
    private BlTzxmDao blTzxmDao;
    @Autowired
    private ServiceSiteDao serviceSiteDao;

    @GetMapping("test")
    public void queryAddress() {
        Example example = new Example(QyNdxx.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("year","2019");
        criteria.andEqualTo("syscFlag","02");
//        criteria.andIsNull("address");
        List<QyNdxx> qyNdxxDaos = ndxxDao.selectByExample(example);
        if(!CollectionUtils.isEmpty(qyNdxxDaos)){
            qyNdxxDaos.forEach(item -> {
//                querylonlat(item);
                if(item.getSyscFlag()!= "01"){
                    try {
                        queryByGaode(item);
                    } catch (UnsupportedEncodingException e) {
                        log.info(e.getMessage());
                    }
                }
                ndxxDao.updateByPrimaryKey(item);
            });
        }
        log.info("结束");

    }

    /**
     * 服务网点
     */
    @GetMapping("yghServiceSite")
    public void yghServiceSite() {
        Example example = new Example(ServiceSite.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNull("lon");
        criteria.andEqualTo("typeId","2");
        List<ServiceSite> serviceSites = serviceSiteDao.selectByExample(example);
        if(!CollectionUtils.isEmpty(serviceSites)){
            serviceSites.forEach(item -> {
                try {
                    String lngAndLag = AmapUtil.getLngAndLagServiceSite(item);
                    if(StringUtils.isEmpty(lngAndLag)){
                        return;
                    }
                    String[] split = lngAndLag.split(",");
                    if(split == null|| split.length != 2){
//                        item.setAddress(null);
                        return;
                    }
//                    double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
                    item.setLon(""+split[0]);
                    item.setLat(""+split[1]);
                    item.setServiceTime("1");
                    log.info("高德 lon:{},lat:{}",split[0],split[1]);
                } catch (UnsupportedEncodingException e) {
                    log.info(e.getMessage());
                }
                serviceSiteDao.updateByPrimaryKey(item);
            });
        }
        log.info("结束");

    }


    /**
     * 服务网点 百度转高德
     */
    @GetMapping("yghServiceSiteFromBd")
    public void yghServiceSiteFromBd() {
        Example example = new Example(ServiceSite.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andIsNull("lon");
        criteria.andEqualTo("typeId","3");
        List<ServiceSite> serviceSites = serviceSiteDao.selectByExample(example);
        if(!CollectionUtils.isEmpty(serviceSites)){
            serviceSites.forEach(item -> {
                try {
                    Map<String, String> stringStringMap = AmapUtil.bd2gd(item.getLon(), item.getLat());
                    if(StringUtils.isEmpty(stringStringMap)){
                        return;
                    }
                    item.setLon(""+stringStringMap.get("lon"));
                    item.setLat(""+stringStringMap.get("lat"));
                    item.setServiceTime("联系电话："+item.getServiceTime());
                    log.info("高德 {}",stringStringMap);
                } catch (Exception e) {
                    log.info(e.getMessage());
                }
                serviceSiteDao.updateByPrimaryKey(item);
            });
        }
        log.info("结束");

    }

    @GetMapping("queryAddressByName")
    public void queryAddressByName(String qymc,String name) {
        Example example = new Example(QyNdxx.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qymc",qymc);
        List<QyNdxx> qyNdxxDaos = ndxxDao.selectByExample(example);
        if(!CollectionUtils.isEmpty(qyNdxxDaos)){
            qyNdxxDaos.forEach(item -> {
                // 天地图
//                querylonlat(item);
                if(item.getSyscFlag()!= "01"){
                    try {
                        queryByGaodeByName(item,name);
                    } catch (UnsupportedEncodingException e) {
                        log.info(e.getMessage());
                        e.printStackTrace();
                    }
                }
                ndxxDao.updateByPrimaryKey(item);
            });
        }
        log.info("结束");

    }

    @GetMapping("queryCxzyLon")
    public void queryCxzyQyMdLonAndLat(){
        Example example = new Example(QyCxzyMd.class);
        Example.Criteria criteria = example.createCriteria();
        // 条件
        List<QyCxzyMd> qyCxzyMds = cxzyMdMapper.selectByExample(example);
        qyCxzyMds.forEach(item ->{
            String lngAndLag = null;
            try {
                lngAndLag = AmapUtil.getCxzyLngAndLag(item);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            if(StringUtils.isEmpty(lngAndLag)){
                item.setLon(null);
                item.setLat(null);
                log.info("高德 地址:{} 无经纬度",item.getQymc());
                cxzyMdMapper.updateByPrimaryKey(item);
                return;
            }
            String[] split = lngAndLag.split(",");
            if(split == null|| split.length != 2){
                return;
            }
            double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            item.setLon(""+doubles[0]);
            item.setLat(""+doubles[1]);
            log.info("高德 地址:{}, lon:{},lat:{}",item.getQymc(),doubles[0],doubles[1]);
            cxzyMdMapper.updateByPrimaryKey(item);
        });
        log.info("查询结束");
    }

    @GetMapping("queryBlTzxmLon")
    public void queryBlTzxmLonLonAndLat(){
        Example example = new Example(BlTzxm.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNull("lon");
        // 条件
        List<BlTzxm> blTzxms = blTzxmDao.selectByExample(example);
        blTzxms.forEach(item ->{
            String lngAndLag = null;
            try {
                lngAndLag = AmapUtil.getCxzyLngAndLag(item);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            if(StringUtils.isEmpty(lngAndLag)){
                item.setLon(null);
                item.setLat(null);
                log.info("高德 地址:{} 无经纬度",item.getQymc());
                blTzxmDao.updateByPrimaryKey(item);
                return;
            }
            String[] split = lngAndLag.split(",");
            if(split == null|| split.length != 2){
                return;
            }
            double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            item.setLon(""+doubles[0]);
            item.setLat(""+doubles[1]);
            log.info("高德 地址:{}, lon:{},lat:{}",item.getQymc(),doubles[0],doubles[1]);
            blTzxmDao.updateByPrimaryKey(item);
        });
        log.info("查询结束");
    }


    @GetMapping("queryXwyLon")
    public void queryXwyLonAndLat(String sql,String queryName){
        Example example = new Example(QyXwyq.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(sql)){
            criteria.andCondition(sql);
        }
        // 条件
        List<QyXwyq> qyXwyqs = qyXwyqDao.selectByExample(example);
        qyXwyqs.forEach(item ->{
            String lngAndLag = null;
            try {
                if(StringUtil.isNotEmpty(queryName)){
                    lngAndLag = AmapUtil.getXwyLngAndLag(item,queryName);
                }else{
                    lngAndLag = AmapUtil.getXwyLngAndLag(item,item.getParkName());
                }
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            if(StringUtils.isEmpty(lngAndLag)){
                item.setLng(null);
                item.setLat(null);
                log.info("高德 地址:{} 无经纬度",item.getParkName());
                qyXwyqDao.updateByPrimaryKey(item);
                return;
            }
            String[] split = lngAndLag.split(",");
            if(split == null|| split.length != 2){
                return;
            }
            double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            item.setLng(""+doubles[0]);
            item.setLat(""+doubles[1]);
            log.info("高德 地址:{}, lon:{},lat:{}",item.getParkName(),doubles[0],doubles[1]);
            qyXwyqDao.updateByPrimaryKey(item);
        });
        log.info("查询结束");
    }

    @GetMapping("queryCggLon")
    public void queryCggLonAndLat(String sql,String queryName){
        Example example = new Example(QyCgg.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(sql)){
            criteria.andCondition(sql);
        }
        // 条件
        List<QyCgg> qyXwyqs = qyCggDao.selectByExample(example);
        qyXwyqs.forEach(item ->{
            String lngAndLag = null;
            try {
                if(StringUtil.isNotEmpty(queryName)){
                    lngAndLag = AmapUtil.getCggLngAndLag(item,queryName);
                }else{
                    lngAndLag = AmapUtil.getCggLngAndLag(item,item.getAddress());
                }
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            if(StringUtils.isEmpty(lngAndLag)){
                item.setLng(null);
                item.setLat(null);
                log.info("高德 地址:{} 无经纬度",item.getXmmc());
                qyCggDao.updateByPrimaryKey(item);
                return;
            }
            String[] split = lngAndLag.split(",");
            if(split == null|| split.length != 2){
                return;
            }
            double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            item.setLng(""+doubles[0]);
            item.setLat(""+doubles[1]);
            log.info("高德 地址:{}, lon:{},lat:{}",item.getXmmc(),doubles[0],doubles[1]);
            qyCggDao.updateByPrimaryKey(item);
        });
        log.info("查询结束");
    }


    /**
     * 高德
     * @param item
     * @throws UnsupportedEncodingException
     */
    private void queryByGaode(QyNdxx item) throws UnsupportedEncodingException {
        String lngAndLag = AmapUtil.getLngAndLag(item);
        if(StringUtils.isEmpty(lngAndLag)){
            item.setAddress(null);
            item.setSyscFlag("02");
            return;
        }
        String[] split = lngAndLag.split(",");
        if(split == null|| split.length != 2){
            item.setAddress(null);
            item.setSyscFlag("02");
            return;
        }
        double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
        item.setLon(""+doubles[0]);
        item.setLat(""+doubles[1]);
        log.info("高德 lon:{},lat:{}",doubles[0],doubles[1]);
        item.setSyscFlag("01");
    }
    /**
     * 高德
     * @param item
     * @throws UnsupportedEncodingException
     */
    private void queryByGaodeByName(QyNdxx item,String name) throws UnsupportedEncodingException {
        if(StringUtil.isEmpty(name)){
            name = item.getQymc();
        }
        String lngAndLag = AmapUtil.getLngAndLagByName(item,name);
        if(StringUtils.isEmpty(lngAndLag)){
            item.setAddress(null);
            item.setSyscFlag("02");
            log.error("无结果");
            return;
        }
        String[] split = lngAndLag.split(",");
        if(split == null|| split.length != 2){
            item.setAddress(null);
            item.setSyscFlag("02");
            log.error("无结果");
            return;
        }
        double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
        item.setLon(""+doubles[0]);
        item.setLat(""+doubles[1]);
        log.info("高德 查询地址:{} lon:{},lat:{}",name,doubles[0],doubles[1]);
        item.setSyscFlag("01");
    }

    public static void main(String[] args) {

//        String a = "宁波市北仑区戚家山街道开发区联合区域工业区G7区花浦路28号1231231";
//        if(a.contains("号")){
//            a = a.split("号")[0].toString() + '号';
//        }

        String lngAndLag = "121.706921,29.909618";
        String[] split = lngAndLag.split(",");
        double[] doubles = AmapUtil.gcj02ToWgs(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
        System.out.println("高德 lon:"+doubles[0]+",lat:"+doubles[1]);

    }



}
